<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * home.php
 *
 * The home controller
 *
 * @author Simon Emms <simon@simonemms.com>
 */
class home extends CI_Controller {
    
    
    
    
    public function backup() {
        exit('backup');
    }
    
    
    
    
    
    
    /**
     * Close Connection
     * 
     * Closes the given connection
     * 
     * @param string $id
     */
    public function close_connection($id = null) {
        
        if(is_null($id)) {
            /* Close all connections */
            $this->database->logout();
        } else {
            /* Close the specified connection */
            $this->database->close_connection($id);
        }
        
        /* Where do we redirect to */
        $redirect = $this->session->flashdata($this->config->item('session_referrer'));
        
        if($redirect === false || $this->input->rest($this->config->item('connection', 'rest'), true, $redirect) == $id) {
            /* Homepage - redirect is either false or the connection we've closed */
            $redirect = site_url();
        }
        
        redirect($redirect);
    }
    
    
    
    
    
    /**
     * Connect
     * 
     * Connect to the API 
     */
    public function connect() {
        if($this->api_connect->can_connect() && $this->api_connect->is_logged_in() === false) {
            /* Can connect and not logged in */
            $this->api_connect->set_callback(site_url('login-callback'));
            
            $this->api_connect->login();
        } else {
            /* No login to do - homepage */
            redirect(site_url());
        }
    }
    
    




    /**
     * Index
     *
     * Index page of the controller
     *
     * @author Simon Emms <simon@simonemms.com>
     */
    public function index() {
        
        /* Check for the cookie - if we do an AJAX query but get logged out */
        $connection_id = $this->input->cookie($this->config->item('session_logout_connection'));
        if($connection_id !== false) {
            /* There's a connection - check we're logged in to that DB */
            if(array_key_exists($connection_id, $this->database->fetch_connections())) {
                /* Yes - override the values then */
                $arrCookie = array(
                    'db' => $this->input->cookie($this->config->item('session_logout_db')),
                    'query' => $this->input->cookie($this->config->item('session_logout_query')),
                );
                
                /* Delete the cookies */
                delete_cookie($this->config->item('session_logout_connection'));
                delete_cookie($this->config->item('session_logout_db'));
                delete_cookie($this->config->item('session_logout_query'));
                
                /* Connection */
                $url = $this->input->rest_replace($this->config->item('connection', 'rest'), $connection_id);
                
                /* Database */
                $url = $this->input->rest_replace($this->config->item('database', 'rest'), $arrCookie['db'], $url);
                
                /* Query - double URL encode this */
                $url = $this->input->rest_replace($this->config->item('query', 'rest'), urlencode($arrCookie['query']), $url);
                
                /* Redirect to the query page */
                redirect($url);
            }
        }
        
        /* Load stuf */
        $this->load->form('general');
        
        /* Get the databases and tables */
        $arrStructure = $this->database->fetch_structure();
        
        /* REST names */
        $arrSelected = array(
            'db' => $this->input->rest($this->config->item('database', 'rest')),
            'tbl' => $this->input->rest($this->config->item('table', 'rest')),
            'query' => $this->input->rest($this->config->item('query', 'rest')),
        );
        
        /* Do we get the structure of a table */
        $arrTable = false;
        $arrQuery = false;
        if($arrSelected['db'] !== false) {
            /* DB specified - set DB */
            $this->database->use_database($arrSelected['db']);
            
            if($arrSelected['tbl'] !== false) {
                $arrTable = $this->database->fetch_table($arrSelected['db'], $arrSelected['tbl']);
            }
            
            if($arrSelected['query'] !== false) {
                $arrQuery = $this->database->execute($arrSelected['db'], urldecode($arrSelected['query']));
            }
        }
        
        /* Get the SQL form */
        $arrSQLForm = $this->general_form->sql_query($arrSelected['query']);
        
        /* Get the query history */
        $arrHistory = $this->database->queries();
        
        /* Get the controls */
        $connection_id = $this->database->db(true);
        $arrControls = array(
            'user' => $this->input->rest_replace($this->config->item('connection', 'rest'), $connection_id, user_management_url()),
            'download' => $this->input->rest_replace($this->config->item('connection', 'rest'), $connection_id, backup_db_url()),
            'upload' => $this->input->rest_replace($this->config->item('connection', 'rest'), $connection_id, restore_db_url()),
            'help' => '#',
        );
        
        /* Get the results tabs */
        $arrResultsTabs = array(
            array(
                'id' => 'results_tabs_table_data',
                'url' => $this->input->rest_replace($this->config->item('sql_tab', 'rest'), 'table'),
                'selected' => $this->input->rest($this->config->item('sql_tab', 'rest')) == 'table' || $this->input->rest($this->config->item('sql_tab', 'rest')) === false,
                'class' => '',
            ),
            array(
                'id' => 'results_tabs_results',
                'url' => $this->input->rest_replace($this->config->item('sql_tab', 'rest'), 'results'),
                'selected' => $this->input->rest($this->config->item('sql_tab', 'rest')) == 'results' || $arrQuery !== false,
                'class' => '',
            ),
            array(
                'id' => 'results_tabs_structure',
                'url' => $this->input->rest_replace($this->config->item('sql_tab', 'rest'), 'structure'),
                'selected' => $this->input->rest($this->config->item('sql_tab', 'rest')) == 'structure',
                'class' => '',
            ),
        );
        
        if($arrQuery !== false) {
            $arrResultsTabs[] = array(
                'id' => 'results_tabs_clear',
                'url' => '#',
                'selected' => false,
                'class' => 'showJS',
            );
        }
        
        /* Get the page title */
        $pagetitle = $this->database->connection_name();
        if($arrSelected['db'] !== false && $arrSelected['tbl'] !== false) {
            $pagetitle = $arrSelected['db'].' ~ '.$arrSelected['tbl'];
        } elseif($arrSelected['db'] !== false) {
            $pagetitle = $arrSelected['db'];
        }
        
        /** Display Data **/
        $this->load->view('home/index', array(
            'pagetitle' => $pagetitle,
            'root' => $this->database->connection_name(),
            'structure' => $arrStructure,
            'table' => $arrTable,
            'history' => $arrHistory,
            'selected' => $arrSelected,
            'sql_form' => $arrSQLForm,
            'sql_query' => $arrQuery,
            'controls' => $arrControls,
            'results_tabs' => $arrResultsTabs,
        ));

    }
    
    
    
    
    
    
    
    
    /**
     * Login
     * 
     * Logs into the database 
     */
    public function login() {
        
        /* Load stuff */
        $this->load->library('api_connect');
        $this->load->form('general');
        
        /* Get the login form */
        $arrForm = $this->general_form->login();
        
        /** Display Data **/
        $this->load->ui('js', 'js/plugins/jquery.oauthpopup');
        $this->load->ui('js', 'js/home/login');
        
        $this->load->view('home/login', array(
            'form' => $arrForm,
            'api_can_connect' => $this->api_connect->can_connect(),
            'api_logged_in' => $this->api_connect->is_logged_in(), /* Are we logged into the API */
            'pagetitle' => $this->lang->line('home_login_pagetitle'),
        ));
    }
    
    
    
    
    
    
    
    public function login_callback() {
        
        /** Display Data **/
        $this->load->ui('js', 'js/home/login_callback');
        
        $this->load->view('home/login_callback', array(
            'pagetitle' => $this->lang->line('home_login_callback_pagetitle'),
        ));
        
    }
    
    
    
    
    
    
    
    /**
     * Logout
     * 
     * Logout from the databases
     */
    public function logout($type = null) {
        $redirect = $this->session->flashdata($this->config->item('session_referrer'));
        
        if($type == 'api') {
            /* Logout from API */
            $this->api_connect->logout();
        } else {
            /* Logout from site */
            $this->load->model('database');

            $this->database->logout();
        }
        
        if($redirect === false) { $redirect = site_url(); }
        
        redirect($redirect);
    }
    
    
    
    
    
    
    
    
    /**
     * New Connection
     * 
     * Manages new database connections 
     */
    public function new_connection() {
        
        /* Load stuff */
        $this->load->form('general');
        
        $arrForm = $this->general_form->new_connection();
        
        /** Display Data **/
        $this->load->ui('js', 'js/home/login');
        
        $this->load->view('home/new_connection', array(
            'pagetitle' => '$pagetitle',
            'form' => $arrForm,
        ));
    }
    
    
    
    
    
    
    public function restore() {
        exit('restore');
    }
    
    
    
    
    
    
    
    public function user_management() {
        exit('user management');
    }

}
?>